package com.blb.examsystem.controller;

import com.blb.common.controller.BaseServlet;
import com.blb.common.entity.User;
import com.blb.common.entity.VO.UserVO;
import com.blb.common.utils.CookieUtil;
import com.blb.common.utils.SpringUtils;

import com.blb.examsystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class UserServlet {
    @Autowired
    private UserService userService ;

    //登录
    @RequestMapping(value = "/login" ,method = RequestMethod.POST)
    public String login(UserVO userVO , HttpSession session , Model model) throws ServletException, IOException {
        //登录验证
        User user= userService.login(userVO.getUsername(),userVO.getPassword());
        //获得Session中的验证码
        String code2 = (String) session.getAttribute("code");
        if(code2 == null || !code2.equals(userVO.getCode())){
            //验证码错误
            model.addAttribute("msg","验证码错误");
            //跳转到登录页面
            return "forward:/index.html";
        }
        if(user != null){
            //将用户信息保存到Session中
            session.setAttribute("user",user);
            //跳转学生管理
            return "redirect:/management.html";
        }else{
            //添加错误信息
            model.addAttribute("msg","账号或密码错误");
            //跳转到登录页面
            return "forward:/index.html";
        }
    }

    //注册
    public void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String nickname = req.getParameter("nickname");
        String cellphone = req.getParameter("cellphone");
//        User user = new User(username, password,nickname,cellphone,1);
        //添加到数据库
//        int rows = userService.addUser(user);
//        if (rows>0){
//            resp.sendRedirect("/index.jsp");
//        }
    }
}
